module.exports = app => {
    const express = require('express')
    const order = require('../../models/Order')
    const money = require('../../models/money')
    const router = express.Router({
        mergeParams: true
    })

    router.get('/order',async(req,res) => {
        await order.find({'status': {$ne:'待支付'}}).populate({path:'goods_list.id'}).exec((err,order)=>{
            err ? res.send('服务器错误...') : res.send(order)
        })
    })
 
    router.get('/order/bill',async(req,res) => {
        var start = new Date(req.query.time.toString()+' 00:00:00')
        var end = new Date(req.query.time.toString()+' 23:59:59')
        await order.find({'order_time':{$gte: start,$lte: end},'status': {$ne:'待支付'}}).populate({path:'goods_list.id'}).exec((err,order)=>{
            err ? res.send('服务器错误...') : res.send(order)
        })
    })

    router.get('/order/time',async(req,res) => {
        await order.find({'status': {$ne:'待支付'},"address.local":req.query.address}).populate({path:'goods_list.id'}).exec((err,order)=>{
            let a = order.filter(item=>{
                return JSON.stringify(item.order_time).split('T')[0].split('"')[1] == req.query.time
            })
            err ? res.send('服务器错误...') : res.send(a)
        })
    })

    router.put('/order',async(req,res) => {
        const { _id, a_status } = req.body
        if(a_status == "配送完毕"){
            await order.updateOne({_id: _id}, {$set: {a_status: a_status,status: a_status}},err=>{
                err ? res.send('服务器错误...') : res.send(a_status)
            })
        }else{
        await order.updateOne({_id: _id}, {$set: {a_status: a_status}},err=>{
            err ? res.send('服务器错误...') : res.send(a_status)
        })
    }
    })
    router.put('/orders',async(req,res) => {
        const {data, a_status } = req.body
        console.log(data)
          var datas =  await order.findByIdAndUpdate({_id: data._id}, {$set: {a_status: a_status,status: a_status}})
          console.log(datas)
        var local = datas.address[0].local
var cash_fee = data.cash_fee
var title = '订单提成'
var addresses = [{
    articleid:datas._id,
    cash_fee:cash_fee,
    title:title,
    accomplish_time:new Date()
}]
console.log("local="+local)
console.log("cash_fee="+cash_fee)
console.log("address="+addresses)
                     await money.update({local:local},{$inc:{"moneys":cash_fee}},{upsert:true})
         var datass= await money.update({local:local},{$addToSet:{"list":addresses}})
         res.send(datass)
    })
//钱包余额
    router.get('/getwall',async(req,res) => {
        var local = req.query.local;
        await money.find({'local': local}).exec((err,wall)=>{
            err ? res.send('服务器错误...') : res.send(wall)
        })
    })

    app.use('/api/admin',router)
}